<script setup lang='ts' name="platform-page">
import { exploitAddGroup, exploitDelGroup, exploitGetGroup, exploitGetGroupNo } from '@fl/api/exploit-setting'
import UpdatedOss from '@fl/components/upLoad-oss.vue'
import { ElButton, ElCard, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus'
import { computed, ref, watch } from 'vue'

import { useForm } from './hooks/use-form'
import listItem from './list.vue'
import TreeItem from './tree.vue'

const props = withDefaults(defineProps<{
    appItem?: any
}>(), {
    appItem: {},
})

const { formRef, rules, state } = useForm()

const { appItem } = toRefs(props)

const form = ref({ ...state })
const filterText = ref('')
const treeRef = ref()
const listRef = ref()
const show = ref(false)
const treeData = ref<any>([])

const getTreeData = computed(() => {
    if (filterText.value) {
        const target: any = []
        treeData.value.forEach((v: any) => {
            // eslint-disable-next-line unicorn/prefer-includes
            if (v.groupName && v.groupName.indexOf(filterText.value) !== -1)
                target.push(v)

            // eslint-disable-next-line unicorn/prefer-includes
            if (v.menuName && v.menuName.indexOf(filterText.value) !== -1)
                target.push(v)
        })

        return target
    }
    return treeData.value
})

async function createSection() {
    const groupCode = await exploitGetGroupNo({
        appId: appItem.value.id,
    })

    form.value = { ...state, groupCode }
    show.value = true
}

function close() {
    show.value = false
}

async function getDataTree(appCode: any) {
    exploitGetGroup({ appCode }).then((res: any) => {
        treeData.value = res
    })
}

function removeTree(data: any) {
    ElMessageBox.confirm(
        '该操作将永久删除，是否继续?',
        '提示',
        {
            type: 'warning',
        },
    )
        .then(() => {
            exploitDelGroup({ id: data.id }).then(() => {
                getDataTree(appItem.value.appCode)
            })
        })
}

async function rowClick(item: any) {
    listRef.value.getData({
        groupId: item.id,
    })
}

async function doAction({ item, type }) {
    if (type === 'edit') {
        form.value = { ...item }
        show.value = true
    }
    else { removeTree(item) }
}

async function doSave(formEl: any) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const appCode = appItem.value.appCode
            exploitAddGroup({
                appCode,
                ...form.value,
            }).then((res: any) => {
                if (res.code === 200) {
                    show.value = false
                    ElMessage.success('保存成功')
                    getDataTree(appCode)
                }

                else { ElMessage({ message: res.msg, type: 'error' }) }
            }).catch((err) => {
                const message = err?.response?.data?.message || err
                ElMessage({ message, type: 'error' })
            })
        }

        else { console.log('error submit!', fields) }
    })
}

watch(appItem, (val: any) => {
    if (val?.appCode)
        getDataTree(val.appCode)
}, {
    deep: true,
    immediate: true,
})
</script>

<template>
    <div flex>
        <ElCard class="left-card"
                style="width:20%;height: 100vh;"
                mr-20
        >
            <div style="padding: 20px;"
                 flex
            >
                <ElInput v-model="filterText" />

                <ElButton ml-6
                          class="el-button el-button--primary el-button--default"
                          @click="createSection"
                >
                    新增分组
                </ElButton>
            </div>

            <TreeItem ref="treeRef"
                      :data="getTreeData"
                      @do-action="doAction"
                      @row-click="rowClick"
            />
        </ElCard>

        <ElCard style="width:80%">
            <listItem ref="listRef"
                      :data="appItem"
            />
        </ElCard>

        <ElDialog v-model="show"
                  width="600"
                  :close-on-click-modal="false"
                  title="新增分组"
                  @close="close"
        >
            <ElForm ref="formRef"
                    :model="form"
                    :rules="rules"
                    label-width="auto"
                    style="max-width: 500px"
            >
                <ElFormItem label="分组名称"
                            prop="groupName"
                >
                    <ElInput v-model="form.groupName" />
                </ElFormItem>

                <ElFormItem label="分组编码"
                            prop="groupCode"
                >
                    <ElInput v-model="form.groupCode"
                             :disabled="true"
                    />
                </ElFormItem>

                <ElFormItem label="分组图标"
                            prop="groupPath"
                >
                    <UpdatedOss v-model="form.groupPath"
                                accept=".png,.jpg,.jpeg"
                    />
                </ElFormItem>

                <!-- <ElFormItem label="排序号"
                            prop="sort"
                >
                    <ElInputNumber v-model="form.sort"
                                   :precision="0"
                                   :step="1"
                    />
                </ElFormItem> -->

                <ElFormItem flex
                            flex-col
                >
                    <ElButton type="primary"
                              @click="doSave(formRef)"
                    >
                        确定
                    </ElButton>

                    <ElButton @click="close">
                        取消
                    </ElButton>
                </ElFormItem>
            </ElForm>
        </ElDialog>
    </div>
</template>

<style lang="less">
.left-card {
    .el-card__body {
        padding: 0;
    }
}

.role-tree {
    max-width: 600px;
}
</style>
